﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.Eartag.API.Application.Command.LamBingCommand;
using S.Eartag.Domain.Model;
using S.Eartag.Infrastructure.Impl;
using S.Eartag.Infrastructure.Interface;

namespace S.Eartag.API.Application.CommandHandlers.LamBingCommandHandler
{
    public class LamBingCreateCommandHandler : IRequestHandler<LamBingCreateCommand, int>
    {
        private readonly ILamBingRepository lamBingRepository;
        private readonly IMapper mapper;

        public LamBingCreateCommandHandler(ILamBingRepository lamBingRepository, IMapper mapper)
        {
            this.lamBingRepository = lamBingRepository;
            this.mapper = mapper;
        }

        public async Task<int> Handle(LamBingCreateCommand request, CancellationToken cancellationToken)
        {
            if (request.Addmode)
            {
                var res = lamBingRepository.All().Result.Where(x => x.EarNumber == request.EarNumber).FirstOrDefault();

                var count = lamBingRepository.All().Result.Where(x => x.EarNumber == request.EarNumber).Count();
                if (count>0)
                {
                    return -2;
                }
                if (res != null)
                {
                    return -1;
                }
                request.CreateBy = "张三";
                request.CreateDate = DateTime.Now;
                
                return await lamBingRepository.Create(mapper.Map<LamBing>(request));
            }
            else
            {
                for (int i=1;i<=request.Earnumbers;i++)
                {
                        var res = lamBingRepository.All().Result.Where(x => x.EarNumber ==request.EarNumber).FirstOrDefault();
                        request.EarNumber = request.Earprefix + request.Startinglug.ToString();
                        request.Startinglug++;
                        request.CreateBy = "张三";
                        request.CreateDate = DateTime.Now;
                        request.UseCondition = 1;

                    var count = lamBingRepository.All().Result.Where(x => x.EarNumber == request.EarNumber).Count();
                    if (count > 0)
                    {
                        return -2;
                    }
                    await  lamBingRepository.Create(mapper.Map<LamBing>(request));
                }
                return 1;
            }
        }
        
    }
}
